﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using WebSOAPUI.Lib;
using WebSOAPUI.Lib.Model;

namespace WebSOAPUI
{
    /// <summary>
    /// Summary description for UploadHandler
    /// </summary>
    public class UploadHandler : IHttpHandler
    {
        private static string[] FILE_EXTENSIONS = ConfigurationManager.AppSettings["fileExtensions"].Split(',');

        public void ProcessRequest(HttpContext context)
        {
            if (!context.Request.IsAuthenticated)
            {
                context.Response.StatusCode = 401;
                context.Response.End();
                return;
            }

            if (context.Request.Files.Count > 0)
            {
                HttpFileCollection files = context.Request.Files;
                var wsID = context.Request.Form["wsID"].ToInt();
                using (var dbContext = new CNOOCDbContext())
                {
                    for (int i = 0; i < files.Count; i++)
                    {
                        HttpPostedFile file = files[i];
                        if (this.ValidExtension(file.FileName))
                        {
                            byte[] buf = new byte[file.InputStream.Length];
                            if (file.InputStream.CanRead)
                            {
                                file.InputStream.Seek(0, 0);
                                file.InputStream.Read(buf, 0, buf.Length);
                            }
                            var attachmentObj = new WebServiceAttachment()
                            {
                                FileName = file.FileName,
                                WebServiceEntityID = wsID,
                                BinData = buf,
                                CreatedOn = DateTime.Now
                            };
                            dbContext.WebServiceAttachments.Add(attachmentObj);
                        }
                        //string fname = context.Server.MapPath("Uploads" + "\\" + file.FileName);
                        //file.SaveAs(fname);
                    }
                    dbContext.SaveChanges();
                }

            }
            context.Response.ContentType = "text/plain";
            context.Response.Write("File/s uploaded successfully!");
        }

        protected bool ValidExtension(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                return false;
            }
            var ext = Path.GetExtension(fileName).Replace(".", "");

            return FILE_EXTENSIONS.ToList().Exists(it => it.EqualsIgnoreCase(ext));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}